package com.piece.core.web.initializer;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import java.util.Comparator;
import java.util.List;

/**
 * 系统功能初始化
 */
@Slf4j
public class SystemInitializer implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired(required = false)
    private List<SystemScript> systemScript;

    public void init() {
        log.info("加载 SystemInitializer ...");
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (CollectionUtils.isNotEmpty(systemScript)) {
            systemScript.sort(Comparator.comparing(SystemScript::getIndex));

            systemScript.stream().forEach(script -> {
                log.info("加载 SystemInitializer --> {}", script.getScriptName());
                try {
                    script.doInit();
                } catch (Exception e) {
                    log.error("应用脚本[{}]初始化失败{}", script.getClass().getSimpleName(), e);
                }
            });
        }
    }
}
